package cn.intotw.pp.server.core;

import cn.intotw.pp.entity.request.ServerBaseReq;
import cn.intotw.pp.entity.response.ServerBaseRes;
import cn.intotw.pp.server.config.SpringConfiguer;
import cn.intotw.pp.server.handler.ServerBaseHandler;
import cn.intotw.pp.util.StringUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.log4j.Log4j;

/**
 * @author Chenxiang
 * @Description: PP服务端handler
 * @create 2018/8/21 14:43
 */
@Log4j
public class PPServerHandler extends SimpleChannelInboundHandler<ServerBaseReq> {
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }
    
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ServerBaseReq serverBaseReq) throws Exception {
        ServerBaseRes serverBaseRes=dispatchRequest(serverBaseReq);
        channelHandlerContext.writeAndFlush(serverBaseRes);
    }

    private ServerBaseRes dispatchRequest(ServerBaseReq serverBaseReq) {
        String transCode=serverBaseReq.getTransCode();
        String beanName= StringUtil.firstLetterToLowerCase(transCode+"RequestHandler");
        ServerBaseHandler serverBaseHandler= (ServerBaseHandler) SpringConfiguer.applicationContext.getBean(beanName);

       return serverBaseHandler.handle(serverBaseReq);
    }
}